﻿#include "RecipeDockWidget.h"
#include "ui_RecipeDockWidget.h"
#include <QFileDialog>
#include <QMessageBox>

RecipeDockWidget::RecipeDockWidget(QWidget *parent) :
    QDockWidget(parent),
    ui(new Ui::RecipeDockWidget)
{
    ui->setupUi(this);
    ui->groupBox->setEnabled(false);
    ui->groupBoxMeasureSpec->setEnabled(false);
    m_pDatabase = new SQLiteImplement2;
}

RecipeDockWidget::~RecipeDockWidget()
{
    delete ui;
}

void RecipeDockWidget::on_lineEditCL_editingFinished()
{
    double cl = ui->lineEditCL->text().toDouble();
    ui->lineEditLSL->setText(QString::number( - 0.2));
    ui->lineEditLCL->setText(QString::number(cl - 0.1));
    ui->lineEditUCL->setText(QString::number(cl + 0.1));
    ui->lineEditUSL->setText(QString::number(cl + 0.2));
}

void RecipeDockWidget::attachStageControl(StageControl *control)
{
    m_pStageControl = control;
}

void RecipeDockWidget::attachData(MeasurementData *data)
{
    m_pData = data;
}

void RecipeDockWidget::attachCamera(TisCamera *camera)
{
    m_pCamera = camera;
}

void RecipeDockWidget::on_toolButtonSetDir_clicked()
{
    QString fileName = QFileDialog::getExistingDirectory(NULL,
                                                         u8"选择文件夹",
                                                         "D:/SQLite");
    ui->lineEditDatabasePath->setText(fileName);
}

void RecipeDockWidget::on_pushButtonSetStartPos_clicked()
{
    double m_theoryPos_mm[4], m_encodePos_mm[4];
    m_pStageControl->updatePos(m_theoryPos_mm, m_encodePos_mm);

    ui->lineEditStartX->setText( QString::number(m_encodePos_mm[0],'f'));
    ui->lineEditStartY->setText( QString::number(m_encodePos_mm[1],'f'));
    ui->lineEditStartZ->setText( QString::number(m_encodePos_mm[2],'f'));

    m_pData->currentMeasure().start.exposure = m_pCamera->expoureTime();
//    m_startScale = m_win->getScale();
//    m_startLen = m_win->getLens();
//    m_startIntensity_top = m_win->getIntensity_top();
//    m_startIntensity_bottom = m_win->getIntensity_bottom();
//    m_startExpoureTime = m_win->getExpoureTime();
}

void RecipeDockWidget::on_pushButtonSetEndPos_clicked()
{
    double m_theoryPos_mm[4], m_encodePos_mm[4];
    m_pStageControl->updatePos(m_theoryPos_mm, m_encodePos_mm);

    ui->lineEditEndX->setText( QString::number(m_encodePos_mm[0],'f'));
    ui->lineEditEndY->setText( QString::number(m_encodePos_mm[1],'f'));
    ui->lineEditEndZ->setText( QString::number(m_encodePos_mm[2],'f'));

    m_pData->currentMeasure().end.exposure = m_pCamera->expoureTime();
}

void RecipeDockWidget::on_pushButtonGotoStart_clicked()
{
    double x_mm = ui->lineEditStartX->text().toDouble();
    double y_mm = ui->lineEditStartY->text().toDouble();
    double z_mm = ui->lineEditStartZ->text().toDouble();
    m_pStageControl->moveToPos(x_mm, y_mm, z_mm);
}

void RecipeDockWidget::on_pushButtonGotoEnd_clicked()
{
    double x_mm = ui->lineEditEndX->text().toDouble();
    double y_mm = ui->lineEditEndY->text().toDouble();
    double z_mm = ui->lineEditEndZ->text().toDouble();
    m_pStageControl->moveToPos(x_mm, y_mm, z_mm);
}

void RecipeDockWidget::GUI2Data()
{
    m_pData->setRecipeName(ui->lineEditDatabaseName->text(), 0, ui->textEditDescription->toPlainText()); // RecipeID 填 0， 这个值不会写入数据库

    MeasurePair &p = m_pData->currentMeasure();

    p.name = ui->lineEditMeasureName->text();
    p.side = ui->radioButton_TFT->isChecked();
    p.CL = ui->lineEditCL->text().toDouble();
    p.UCL = ui->lineEditUCL->text().toDouble();
    p.LCL = ui->lineEditLCL->text().toDouble();
    p.USL = ui->lineEditUSL->text().toDouble();
    p.LSL = ui->lineEditLSL->text().toDouble();
    p.start.x_mm = ui->lineEditStartX->text().toDouble();
    p.start.y_mm = ui->lineEditStartY->text().toDouble();
    p.start.z_mm = ui->lineEditStartZ->text().toDouble();
    p.end.x_mm = ui->lineEditEndX->text().toDouble();
    p.end.y_mm = ui->lineEditEndY->text().toDouble();
    p.end.z_mm = ui->lineEditEndZ->text().toDouble();
    p.start.dir = static_cast<MEASURE_DIR>(ui->comboBoxStartDir->currentIndex());
    p.end.dir = static_cast<MEASURE_DIR>(ui->comboBoxEndDir->currentIndex());
    p.start.pattern  = static_cast<MEASURE_PATTERN>(ui->comboBoxStartPattern->currentIndex());
    p.end.pattern  = static_cast<MEASURE_PATTERN>(ui->comboBoxEndPattern->currentIndex());

    p.stop = ui->checkBoxStop->isChecked();
    p.stopMessage = ui->lineEditStopMessage->text();
}


void RecipeDockWidget::data2GUI()
{
    ui->lineEditDatabaseName->setText(m_pData->recipeName());
    ui->textEditDescription->setText(m_pData->description());
    int index = ui->comboBoxMeasureID->currentIndex();
    ui->groupBoxMeasureSpec->setTitle(QString(u8"测点%1").arg(index + 1));
    m_pData->moveTo(index);
    MeasurePair &p = m_pData->currentMeasure();
    ui->lineEditMeasureName->setText(p.name);
    ui->spinBox->setValue(m_pData->count());
    ui->textEditDescription->setText(m_pData->description());
    ui->groupBoxMeasureSpec->setTitle(QString(u8"测点%1").arg(1));
    ui->radioButton_CF->setChecked(p.side == 0);
    ui->radioButton_TFT->setChecked(p.side == 1);
    ui->lineEditCL->setText(QString::number(p.CL,'f'));
    ui->lineEditUCL->setText(QString::number(p.UCL,'f'));
    ui->lineEditLCL->setText(QString::number(p.LCL,'f'));
    ui->lineEditUSL->setText(QString::number(p.USL,'f'));
    ui->lineEditLSL->setText(QString::number(p.LSL,'f'));
    ui->lineEditStartX->setText(QString::number(p.start.x_mm,'f'));
    ui->lineEditStartY->setText(QString::number(p.start.y_mm,'f'));
    ui->lineEditStartZ->setText(QString::number(p.start.z_mm,'f'));
    ui->lineEditEndX->setText(QString::number(p.end.x_mm,'f'));
    ui->lineEditEndY->setText(QString::number(p.end.y_mm,'f'));
    ui->lineEditEndZ->setText(QString::number(p.end.z_mm,'f'));

    ui->comboBoxStartDir->setCurrentIndex(p.start.dir);
    ui->comboBoxStartPattern->setCurrentIndex(p.start.pattern);
    ui->comboBoxEndDir->setCurrentIndex(p.end.dir);
    ui->comboBoxEndPattern->setCurrentIndex(p.end.pattern);

    ui->checkBoxStop->setChecked(p.stop);
    ui->lineEditStopMessage->setText(p.stopMessage);
}

void RecipeDockWidget::on_comboBoxMeasureID_currentIndexChanged(int index)
{
    GUI2Data();
    m_pData->moveTo(index);
    data2GUI();
}

void RecipeDockWidget::on_pushButtonSave_clicked()
{
    //qDebug() <<"on_pushButtonSave_clicked()";
    GUI2Data();
    //qDebug() << "m_database->createRecipe(m_pData, m_fileName);";
    qDebug() << "m_pData->count() = " << m_pData->count();
    int ret = m_pDatabase->createRecipe(m_pData, m_fileName);
    qDebug() << "writeSpec = " << ret;
    if(ret != 1)
    {
        QMessageBox::warning(this, u8"警告", u8"数据库写入失败！");
        return;
    }
    QMessageBox::about(this, u8"提示", u8"全部测点保存完毕");
    ui->pushButtonExit->setEnabled(true);
}

void RecipeDockWidget::on_pushButtonCreateDatabase_clicked()
{
    if( ui->lineEditDatabasePath->text().isEmpty())
    {
        QMessageBox::about(this, u8"提示", u8"请选择或输入目录");
        return;
    }
    QFileInfo fi(ui->lineEditDatabasePath->text());
    if( !fi.isDir() )
    {
        //QMessageBox::about(this, u8"提示", u8"目录不存在");
        int ret = QMessageBox::question(this,
                                        u8"提示",
                                        u8"目录不存在，是否创建",
                                        QMessageBox::Yes | QMessageBox::No,
                                        QMessageBox::Yes);
        if(ret == QMessageBox::Yes)
        {
            QDir dir;
            if(! dir.mkdir(ui->lineEditDatabasePath->text()) )
            {
                QMessageBox::about(this, u8"提示", u8"目录创建失败");
                return;
            }
        }
        else
        {
            QMessageBox::about(this, u8"提示", u8"请重新选择目录");
            return;
        }
        return;
    }
    if( ui->lineEditDatabaseName->text().isEmpty())
    {
        QMessageBox::about(this, u8"提示", u8"数据库名称不能为空");
        return;
    }
    if( ui->spinBox->value() <= 0)
    {
        QMessageBox::about(this, u8"提示", u8"测点数量不能小于等于 0");
        return;
    }
    //创建文件并创建表格写入信息
    m_fileName = ui->lineEditDatabasePath->text() + "/" + ui->lineEditDatabaseName->text() + ".db";
    if( QFileInfo(m_fileName).isFile() )
    {
        int ret = QMessageBox::question(this,
                                        u8"提示",
                                        u8"文件已存在，是否读取？点击 Yes 读取，点击 No 覆盖",
                                        QMessageBox::Yes | QMessageBox::No,
                                        QMessageBox::Yes);
        if(ret == QMessageBox::Yes)
        {
            ui->textEditDescription->clear();
            if( m_pDatabase->loadRecipe(m_pData, m_fileName) == 1)
            {
                data2GUI();
                for(int i = 1; i <= m_pData->count(); i++)
                {
                    ui->comboBoxMeasureID->addItem(QString(u8"测点%1").arg(i));

                }

                ui->groupBoxNewDB->setEnabled(false);
                ui->groupBoxMeasureSpec->setEnabled(true);
                return;
            }
            else
            {
                QMessageBox::about(this, u8"提示", u8"数据库读取失败");
                return;
            }
        }
        else
        {
            QFile file(m_fileName);
            file.remove();
        }
    }
    int N = ui->spinBox->value();
    m_pData->buildData(N);
    ui->groupBoxNewDB->setEnabled(false);
    ui->groupBox->setEnabled(true);
    ui->groupBoxMeasureSpec->setEnabled(true);
    m_pData->setRecipeName(ui->lineEditDatabaseName->text(), 0, ui->textEditDescription->toPlainText());

    for(int i = 1; i <= N; i++)
    {
        ui->comboBoxMeasureID->addItem(QString(u8"测点%1").arg(i));
    }
    ui->comboBoxMeasureID->setCurrentIndex(0);

    data2GUI();
}
